package com.wlyuan.open.scanner.utils;

import java.math.BigDecimal;
import java.util.Optional;

/**
 * @author lijing
 * @description
 */
public class NumberUtils {

    /**
     * bigDecimal处理
     *
     * @param qty
     * @return
     */
    public static BigDecimal changeZero(BigDecimal qty) {
        return Optional.ofNullable(qty).orElse(BigDecimal.ZERO);
    }

    public static BigDecimal changeNull(BigDecimal value) {
        return Optional.ofNullable(value).orElse(null);
    }

    /**
     * 相减
     *
     * @param start
     * @param end
     * @return
     */
    public static BigDecimal sub(BigDecimal start, BigDecimal end) {
        start = changeZero(start);
        end = changeZero(end);
        return start.subtract(end).setScale(2, BigDecimal.ROUND_HALF_UP);
    }

    /**
     * 相减
     *
     * @param start
     * @param end
     * @return
     */
    public static BigDecimal add(BigDecimal start, BigDecimal end) {
        start = changeZero(start);
        end = changeZero(end);
        return start.add(end).setScale(7, BigDecimal.ROUND_HALF_UP);
    }

    /**
     * 回执付款(应收款=总金额-货到付款-预付款-代收货款)
     *
     * @param totalCost 总金额
     * @param payable   货到付款
     * @param payment   预付款
     * @param paySub    代收货款
     * @return
     */
    public static BigDecimal receiptCost(BigDecimal totalCost, BigDecimal payable, BigDecimal payment, BigDecimal paySub) {
        totalCost = changeZero(totalCost);
        payable = changeZero(payable);
        payment = changeZero(payment);
        paySub = changeZero(paySub);
        return totalCost.subtract(payable).subtract(payment).subtract(paySub).setScale(2, BigDecimal.ROUND_HALF_UP);
    }

    public static boolean compareZero(BigDecimal val) {
        return BigDecimal.ZERO.compareTo(changeZero(val)) == 0;
    }

}
